import os
import time
from appium.webdriver import Remote
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from AppFrame.common.logger import FrameLog as   log
from AppFrame.common import  dir_config  as Dir

class BasePage:
    """
    BasePage:定义每个页面的相同属性及方法
    相同属性？获取浏览器驱动对象（数据）
    相同方法？元素定位、点击、输入...等等操作
    日志
    错误截图
    测试报告
    """
    def __init__(self,driver:Remote):
        self.driver=driver



    def locator(self,page_name,loc,):
        """元素定位"""
        # WebElement对象
        try:
            el=self.driver.find_element(*loc)
            log().getLogger().info(f"在[{page_name}]，定位到元素：{loc}")

        except:
            log().getLogger().error(f"在[{page_name}]，未定位到元素：{loc}！！！")
            # 失败截图
            self.sava_page_shot(page_name)
            raise
        return el


    # 等待元素存在
    def wait_ele_visibility(self,page_name,loc,timeout=15,poll_fre=0.5):
        try:
            WebDriverWait(self.driver,timeout,poll_fre).until(EC.visibility_of_element_located(loc))
            # WebElement对象
            log().getLogger().info(f"在[{page_name}]，找到元素：{loc}可见")
        except:
            log().getLogger().error(f"在[{page_name}]，未找到元素：{loc}可见！！！")


    # 等待元素可见
    def wait_ele_presence(self,page_name,loc,timeout=15,poll_fre=0.5):
        try:
            WebDriverWait(self.driver,timeout,poll_fre).until(EC.presence_of_element_located(loc))
            log().getLogger().info(f"在[{page_name}]，找到元素：{loc}存在")
        except:
            log().getLogger().error(f"在[{page_name}]，未找到元素：{loc}存在！！！")


    def input(self,page_name,loc,value):
        """输入"""
        # 等待元素可见
        try:
            self.wait_ele_visibility(page_name,loc)
            self.locator(page_name,loc).send_keys(value)
            log().getLogger().info(f"在{page_name}，元素{loc}输入:{value}！")

        except:
            log().getLogger().error(f"在{page_name}，元素{loc}输入失败！")
            # 失败截图
            self.sava_page_shot(page_name)

    def click(self,page_name,loc):
        """点击"""
        try:
            # 等待元素可见
            self.wait_ele_visibility(page_name,loc)
            self.locator(page_name,loc).click()
            log().getLogger().info(f"在[{page_name}]，点击元素{loc}成功！")
        except:
            log().getLogger().error(f"在[{page_name}]，元素{loc}点击失败！")
            # 失败截图
            self.sava_page_shot(page_name)

    def sleep(self,s):
        time.sleep(s)

    #鼠标键盘操作
    def move_element(self,page_name,loc):
        try:
            # 等待元素可见
            self.wait_ele_visibility(page_name,loc)
            ActionChains(self.driver).move_to_element(self.locator(page_name,loc)).perform()
            log().getLogger().info(f"在[{page_name}]，鼠标移动到元素:{loc}")
        except:
            log().getLogger().error(f"在[{page_name}]，鼠标移动到元素{loc}失败！")
            # 失败截图
            self.sava_page_shot(page_name)


    def sava_page_shot(self,img_name):
        filename=os.path.join(Dir.screen_dir,img_name+'.png')
        self.driver.save_screenshot(filename)
        log().getLogger().info(f"失败截图，截取当前网页，存储的路径:{filename}")

    # appbasepage：
    def get_screensize(self):
        # 获取屏幕的大小
        size = self.driver.get_window_size()
        x = size["width"]
        y = size["height"]
        return x,y

    #滑屏操作  上下左右滑
    def swipe(self,direction,duration=1000):
        """
        :param direction: up  down  left  right
        :param duration:
        :return:
        """
        screen_size=self.get_screensize()
        x=screen_size[0]
        y=screen_size[0]
        # 左滑
        if direction.lower()=='left':
            self.driver.swipe(start_x=x*0.9,end_x=x*0.2,start_y=y*0.8,end_y=y*0.8,duration=duration)
        elif direction.lower()=='right':
            pass
        elif direction.lower()=='up':
            pass
        elif direction.lower()=='down':
            pass
        else:
            raise

    #触屏操作
    #多点触控
    #定位h5元素  微信小程序   切换上下文


# app自动测试 appium
# app自动化测试+web自动测试整合  公共类 basepage  web自动化  webbasepage  app自动化 appbasepage
# 日志+错误截图+测试报告输出
